<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 对话助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* 自定义滚动条样式 */
        .chat-container::-webkit-scrollbar {
            width: 6px;
        }
        .chat-container::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        .chat-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        .chat-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 打字机效果 */
        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0; }
        }
        .typing-cursor {
            display: inline-block;
            width: 8px;
            height: 16px;
            background: #4b5563;
            vertical-align: middle;
            margin-left: 2px;
            animation: blink 1s step-end infinite;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
<header class="bg-white shadow-sm py-4">
    <div class="container mx-auto px-4">
        <h1 class="text-2xl font-bold text-gray-800">AI 对话助手</h1>
    </div>
</header>

<main class="flex-1 container mx-auto px-4 py-6 flex flex-col max-w-3xl">
    <!-- 对话区域 -->
    <div id="chatContainer" class="chat-container flex-1 bg-white rounded-lg shadow-sm p-4 mb-4 overflow-y-auto max-h-[70vh] space-y-4">
        <!-- 对话消息将在这里动态添加 -->
        <div class="text-center text-gray-500 py-8" id="welcomeMessage">
            <p class="text-lg">欢迎使用AI对话助手</p>
            <p class="text-sm mt-2">输入您的问题，我将尽力为您解答</p>
        </div>
    </div>

    <!-- 输入区域 -->
    <div class="bg-white rounded-lg shadow-sm p-4">
        <form id="chatForm" class="flex space-x-2">
            <input
                    type="text"
                    id="userInput"
                    placeholder="输入您的问题..."
                    class="flex-1 border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    autocomplete="off"
                    required
            >
            <button
                    type="submit"
                    id="sendButton"
                    class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-lg transition duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
                发送
            </button>
        </form>
        <p class="text-xs text-gray-500 mt-2">AI可能会犯错，请谨慎验证重要信息</p>
    </div>
</main>

<footer class="bg-white py-4 border-t">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2023 AI对话助手 - 基于流式API实现</p>
    </div>
</footer>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const chatForm = document.getElementById('chatForm');
        const userInput = document.getElementById('userInput');
        const sendButton = document.getElementById('sendButton');
        const chatContainer = document.getElementById('chatContainer');
        const welcomeMessage = document.getElementById('welcomeMessage');

        // 对话历史
        let conversationHistory = [];

        // 发送消息
        chatForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const message = userInput.value.trim();
            if (!message) return;

            // 添加用户消息到对话历史
            addMessageToChat('user', message);
            conversationHistory.push({ role: 'user', content: message });

            // 清空输入框
            userInput.value = '';

            // 禁用输入和按钮
            userInput.disabled = true;
            sendButton.disabled = true;

            // 添加AI消息占位
            const aiMessageId = 'ai-' + Date.now();
            addMessageToChat('ai', '', aiMessageId);

            // 隐藏欢迎消息
            if (welcomeMessage) {
                welcomeMessage.style.display = 'none';
            }

            try {
                // 调用流式API
                await streamAIResponse(message, aiMessageId);
            } catch (error) {
                console.error('API调用失败:', error);
                updateAIMessage(aiMessageId, '抱歉，服务暂时不可用，请稍后再试。', true);
            } finally {
                // 恢复输入和按钮
                userInput.disabled = false;
                sendButton.disabled = false;
                userInput.focus();
            }
        });

        // 添加消息到聊天界面
        function addMessageToChat(role, content, messageId = null) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex ${role === 'user' ? 'justify-end' : 'justify-start'}`;

            const bubble = document.createElement('div');
            bubble.className = `max-w-[80%] rounded-lg px-4 py-2 ${
                role === 'user'
                    ? 'bg-blue-500 text-white rounded-br-none'
                    : 'bg-gray-100 text-gray-800 rounded-bl-none'
            }`;

            if (messageId) {
                bubble.id = messageId;
            }

            if (content) {
                bubble.textContent = content;
            } else if (role === 'ai') {
                // 添加打字动画
                bubble.innerHTML = '<span class="typing-cursor"></span>';
            }

            messageDiv.appendChild(bubble);
            chatContainer.appendChild(messageDiv);

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 更新AI消息
        function updateAIMessage(messageId, newContent, isComplete = false) {
            const messageElement = document.getElementById(messageId);
            if (!messageElement) return;

            if (isComplete) {
                messageElement.innerHTML = newContent || '（无内容）';
            } else {
                // 保留光标如果还没结束
                messageElement.innerHTML = newContent + '<span class="typing-cursor"></span>';
            }

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 流式获取AI响应
        function streamAIResponse(userMessage, messageId) {
            return new Promise((resolve, reject) => {
                // 这里替换为你的实际API URL
                const apiUrl = 'http://localhost:8090/api/v1/ollama/generateStream?model=deepseek-r1:1.5b';

                // 添加请求参数
                const params = new URLSearchParams();
                params.append('message', userMessage);
                // params.append('history', JSON.stringify(conversationHistory));

                const url = `${apiUrl}&${params.toString()}`;

                let fullResponse = '';
                const eventSource = new EventSource(url);

                eventSource.onmessage = (event) => {
                    try {
                        const result = JSON.parse(event.data);
                        const content = result.result.output?.content || '';

                        // 累积响应内容
                        fullResponse += content;
                        console.log("fullResponse = ", fullResponse)
                        updateAIMessage(messageId, fullResponse);

                        // 检查是否结束
                        if (result.metadata?.finishReason === 'STOP') {
                            eventSource.close();
                            updateAIMessage(messageId, fullResponse, true);

                            // 添加AI消息到对话历史
                            conversationHistory.push({ role: 'assistant', content: fullResponse });
                            resolve();
                        }
                    } catch (error) {
                        console.error('解析响应失败:', error);
                        eventSource.close();
                        reject(error);
                    }
                };

                eventSource.onerror = (error) => {
                    console.error('EventSource错误:', error);
                    eventSource.close();

                    if (fullResponse) {
                        updateAIMessage(messageId, fullResponse, true);
                        conversationHistory.push({ role: 'assistant', content: fullResponse });
                        resolve();
                    } else {
                        updateAIMessage(messageId, '抱歉，响应过程中出现了问题。', true);
                        reject(new Error('EventSource错误'));
                    }
                };
            });
        }

        // 初始焦点在输入框
        userInput.focus();
    });
</script>
</body>
</html>